package com.acme.superlogger.slf4j;

import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

class AsyncWriter{


    private final PrintWriter out;
    private final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
    private final AtomicBoolean running = new AtomicBoolean(false);
    private final Writer runnable = new Writer();

    AsyncWriter(PrintWriter writer) {
        this.out = writer;
    }

    public void putLine(String line) {
        try {
            queue.put(line);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!running.get()){
            rerunWriter();
        }
    }

    private void rerunWriter(){
        if(running.compareAndSet(false,true)){
            new Thread(runnable).start();
        }
    }

    private class Writer implements Runnable{
        @Override
        public void run() {
            String line;
            try {
                while((line = queue.poll(100, TimeUnit.MILLISECONDS))!=null){
                    out.println(line);
                    out.flush();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                if(running.getAndSet(false) && !queue.isEmpty()){
                    rerunWriter();
                }
            }
        }
    }

}